﻿ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XSTDZ.ERP.Core.Repositories;
using XSTDZ.ERP.Domain.Models;
using XSTDZ.ERP.Application.DataContracts;
using AutoMapper;
using XSTDZ.ERP.Core.Generator;

namespace XSTDZ.ERP.Application.Implements
{
    public class UserServiceImpl : ApplicationServiceBase, IUserService
    {
        IRepository<User> _userRepository;
        IRepository<UserRole> _userRoleRepository;
        public UserServiceImpl(IRepositoryContext responseContext, IRepository<User> userRepository, IRepository<UserRole> userRoleRepository)
            : base(responseContext)
        {
            this._userRepository = userRepository;
            this._userRoleRepository = userRoleRepository;
        }
       
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Guid AddUser(UserDto userDto)
        {
            var user = Mapper.Map<UserDto, User>(userDto);
            if (user.Id == null || user.Id.Equals(Guid.Empty))
            {
                user.Id = (Guid)new SequentialIdentityGenerator().Next;
            }
            if (!this._userRepository.Exists(t => t.Id == user.Id))
            {
                user.InitUser().AddRoles(userDto.RoleIds);//flunt api
                this._userRepository.Add(user);
                this.Context.Commit();
            }
            return user.Id;
        }
        public void UpdateUser(UserDto userDto)
        {
            var user = Mapper.Map<UserDto, User>(userDto);
          var u=  this._userRepository.GetByKey(userDto.Id);
           user = Mapper.Map(u, user);
           #region 手工赋值
           user.AccountName = userDto.AccountName;
           user.Name = userDto.Name;
           user.Address = userDto.Address;
           user.Birthday = userDto.Birthday;
           user.DeptID = userDto.DeptId;
           user.Email = userDto.Email;
           user.Gender = userDto.Gender;
           user.Mobile = userDto.Mobile;
           user.MSN = userDto.MSN;
           user.OrgID = userDto.OrgId.Value;
           user.Password = userDto.Password;
           user.PostNo = userDto.PostNo;
           user.QQ = userDto.QQ;
           user.Tel = userDto.Tel;
           user.IsPiece = userDto.IsPiece;
           #endregion
           if (user.UserRoles != null && user.UserRoles.Count > 0)
           {
               this._userRoleRepository.Remove(ur=>u.UserRoles.Select(t=>t.Id).ToArray().Contains(ur.Id));
           }
            user.InitUser().ClearAllUserRole().AddRoles(userDto.RoleIds);
            this._userRepository.Update(user);
            this.Context.Commit();
        }
        public UserDto GetUser(string userName, string userPassword)
        {
            var user= this._userRepository.Get(u => u.AccountName == userName && u.Password == userPassword);
            if (user != null)
            {
                if (user.IsUse && user.Deleted != 1)
                {
                    return Mapper.Map<User, UserDto>(user);
                }
            }
            return null;
        }

        public UserDto GetUser(Guid userid)
        {
            var names = "";
            var roleIds =new List<Guid>();
            var user = this._userRepository.GetByKey(userid);
            if (user.UserRoles != null && user.UserRoles.Count() != 0)
            {
                var roleNames = user.UserRoles.Select(t =>t.Role==null?"": t.Role.Description);
                if (roleNames != null)
                {
                    roleIds= user.UserRoles.Select(t =>t.Role==null?Guid.Empty: t.Role.Id).ToList();
                    roleNames.Each(t => names += (string.IsNullOrEmpty(t.ToString())?"": t.ToString()+",") );
                    names = string.IsNullOrEmpty(names) ? "" : names.Substring(0, names.Length - 1);
                }
            }
            var u= Mapper.Map<User, UserDto>(user);
            u.RoleName = names;
            u.RoleIds = roleIds;
            return u;
        }
        public Guid GetUserOrg(Guid userId)
        {
         var user= this._userRepository.GetByKey(userId);
         return user.OrgID;
        }
        public IEnumerable<UserDto> GetAllUser()
        {
            var users = this._userRepository.GetAll();
            return Mapper.Map<IEnumerable<User>, IEnumerable<UserDto>>(users);
        }
        public bool IsAuthoraized(Guid userid, string controllerName, string actionName)
        {
            return true;
            //var user = this._userRepository.GetByKey(userid);
            //var userpermission = user.UserPermission;
            //var userPermission = user.UserPermission.Permissions.Where(p => p.Controller == controllerName && p.Action == actionName).FirstOrDefault();
            //return userPermission.Id.ToString().Length > 0 ? true : false;
        }


        public void DeleteUser(Guid userId)//修改为删除状态的更新
        {
           // this._userRepository.Remove(u => u.Id == userId);
            var user = this._userRepository.GetByKey(userId);
            user.Deleted = 1;
            this._userRepository.Update(user);
            this.Context.Commit();
        }
       
        public void DisableUser(Guid userId,bool isEnable)
        {
            var user = this._userRepository.GetByKey(userId);
            user.IsUse = isEnable;
            this._userRepository.Update(user);
            this.Context.Commit();
        }
        public bool IsExists(string loginName)
        {
            return this._userRepository.Exists(u => u.AccountName == loginName);
        }

        public IEnumerable<Guid> GetUiPermissionIds(Guid userId,string controllerName,string actionName,out bool isExistPermission)
        {
            isExistPermission = false;
           var u= this._userRepository.FindByKey(userId);
            //是否存在页面权限
             var existsPermission = u.UserRoles.Select( t => t.Role.RolePermissions.Select( m=>m.Permission));
            var permissions=new List<Permission>();
            existsPermission.Each(t =>permissions.AddRange(t.ToList()));
            permissions = permissions.Where(m => m.Controller.ToUpper() == controllerName.ToUpper() && m.Action.ToUpper() == actionName.ToUpper()).Select(t => t).Distinct().ToList<Permission>();

            if (permissions.Count() != 0)
            {
                isExistPermission = true;
            }
            return permissions.Where(t => t.Level != 1).Select(m => m.Id);

          
        }
        public IEnumerable<Guid> GetPermissionIds(Guid userId)
        {
            var u = this._userRepository.FindByKey(userId);
            var permissions = u.UserRoles.Select(t => t.Role.RolePermissions.Select(m => m.Permission));
            var permissionIds = new List<Guid>();
            permissions.Each(t => permissionIds.AddRange(t.Where(p => p.Level == 1).Select(n => n.Id).ToList()));

            return permissionIds.Distinct();
        }
    }
}
